package cn.data.collection.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class TextReader {
	/**
	 * 功能：Java读取txt文件的内容 步骤：1：先获得文件句柄 2：获得文件句柄当做是输入一个字节码流，需要对这个输入流进行读取
	 * 3：读取到输入流后，需要读取生成字节流 4：一行一行的输出。readline()。 备注：需要考虑的是异常情况
	 * 
	 * @param filePath
	 * @throws IOException
	 */
	public static String readTxtFile(String filePath) throws IOException {
		FileInputStream fileInputStream = null;
		InputStreamReader read = null;
		BufferedReader bufferedReader = null;
		StringBuffer sb = new StringBuffer(10);
		try {
			String encoding = "GBK";
			File file = new File(filePath);
			if (file.isFile() && file.exists()) { // 判断文件是否存在
				fileInputStream = new FileInputStream(file);
				read = new InputStreamReader(fileInputStream, encoding);// 考虑到编码格式
				bufferedReader = new BufferedReader(read);
				String lineTxt = null;
				while ((lineTxt = bufferedReader.readLine()) != null) {
					sb.append(lineTxt);
				}
			} else {
				throw new IOException("找不到指定的文件");
			}
		} catch (Exception e) {
			throw new IOException("读取文件内容出错");
		} finally {
			if (fileInputStream != null) {
				fileInputStream.close();
				fileInputStream = null;
			}
			if (read != null) {
				read.close();
				read = null;
			}
			if (bufferedReader != null) {
				bufferedReader.close();
				bufferedReader = null;
			}
		}
		return sb.toString();
	}

	public static void main(String[] args) throws IOException {
		String filePath = "temp\\result\\1430908303768.txt";
		// "res/";
		System.out.println(readTxtFile(filePath));
	}
}
